package com.macllvm.whale.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.TextView;
import android.widget.ImageView;
import android.widget.BaseAdapter;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import com.macllvm.whale.entity.Buddy;
import com.macllvm.whale.R;

public class BuddyAdapter extends BaseAdapter {

    private List<Buddy> buddyList;
    private LayoutInflater inflater;

    static class BuddyItemView {
        public ImageView   avatar;
        public TextView    host;
        public TextView    sign;
        public ImageView   state;
        public TextView    unreadCount;
    }

    public BuddyAdapter(Context ctx){
        inflater = LayoutInflater.from(ctx);
    }

    public void setDataSource(List<Buddy> list){
        buddyList = list;
    }

    @Override
    public int getCount() {
        return buddyList.size();
    }

    @Override
    public Object getItem(int position) {
        return buddyList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        BuddyItemView buddyItemView;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.buddy_item, null);
            buddyItemView = new BuddyItemView();
            buddyItemView.avatar = (ImageView)convertView.findViewById(R.id.buddy_avatar);
            buddyItemView.host = (TextView)convertView.findViewById(R.id.buddy_host);
            buddyItemView.sign = (TextView)convertView.findViewById(R.id.buddy_sign);
            buddyItemView.state = (ImageView)convertView.findViewById(R.id.buddy_state);
            buddyItemView.unreadCount = (TextView)convertView.findViewById(R.id.unread_count);
            convertView.setTag(buddyItemView);
        } else {
            buddyItemView = (BuddyItemView)convertView.getTag();
        }

        Buddy b = (Buddy)buddyList.get(position);
        buddyItemView.host.setText(b.getIP() + " " + b.getHostName());
        buddyItemView.sign.setText(b.getSignature());


        if(b.getState() == Buddy.STATE_ONLINE){
            buddyItemView.state.setImageResource(R.drawable.online);
        } else {
            buddyItemView.state.setImageResource(R.drawable.offline);
        }

        int count = b.getUnreadCount();
        if(count > 0) {
            buddyItemView.unreadCount.setText(String.valueOf(count));
            buddyItemView.unreadCount.setVisibility(View.VISIBLE);
        } else {
            buddyItemView.unreadCount.setVisibility(View.INVISIBLE);
        }

        return convertView;
    }

}



